package cn.exrick.xboot.modules.captchaLogin.controller;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.qywxCode.CreateRandomNums;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SpringContextUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.JiGuangPushUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.config.pushCode.jPushConfig;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author    : LiYuanzhuo
 * description: 验证码登录方式
 * create time: 2019/9/18 13:59
 */
@Slf4j
@RestController
@RequestMapping("/ssoLogin")
@CacheConfig(cacheNames = "user")
@EnableTransactionManagement
@Component
public class SendValidateCode {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private jPushConfig config;
    @Autowired
    private UserService userService;


    /**
     * @author    : LiYuanzhuo
     * description: 发送APP验证码
     * create time: 2019/9/3 13:53
     */
    @RequestMapping(value = "/sendCode",method = RequestMethod.POST)
    public Result<Object> sendCode(@RequestParam String username){
        //验证用户名与密码
        User user = userService.findByUsername(username);
        if (user == null) {
            return new ResultUtil<Object>().setErrorMsg("用户不存在");
        }
       //先查找该用户有没有存在缓存验证码
       String oldVCode = stringRedisTemplate.opsForValue().get(SecurityConstant.USER_QYWX + user.getUsername());
       if (oldVCode != null){
           stringRedisTemplate.delete(SecurityConstant.USER_QYWX + user.getUsername());
       }
        String errotMsg = "发送失败！请登录APP后重试！";
        //app动态码登录方式
        try{
            String wxcode = CreateRandomNums.createRandomNum(6);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar afterTime = Calendar.getInstance();
            afterTime.add(Calendar.MINUTE,5);
            Date after=afterTime.getTime();
            String exiperTime = sdf.format(after);
            //发送app验证码
            JPushClient jPushClient = new JPushClient(config.getMasterSecret(),config.getAppKey());

            Map map = new HashMap();
            JSONObject jsonInfo =new JSONObject();
            jsonInfo.put("expireTime",exiperTime);
            jsonInfo.put("code",wxcode);

            map.put("body" ,jsonInfo.toJSONString());//对象数据
            map.put("RequestType" , CommonConstant.APP_CAPTCHA);//推送业务数据类型
            PushResult pushResult = JiGuangPushUtil.pushAPP(jPushClient,"alias",username,map,"Portal动态码：" + wxcode,"【湖南交建】验证码：" +wxcode);
            log.info("极光推送数据返回结果{}",pushResult.toString());
            if(pushResult != null && pushResult.isResultOK()){
                if (pushResult.statusCode == 1){
                    errotMsg = "推送消息未送达";
                }
                if (pushResult.statusCode == 4){
                    errotMsg = "推送系统异常";
                }
                //推送成功，将验证码保存到redis中
                redisTemplate = (RedisTemplate) SpringContextUtil.getBean("redisTemplate");
                RedisSerializer stringSerializer = new StringRedisSerializer();
                redisTemplate.setKeySerializer(stringSerializer);
                redisTemplate.setValueSerializer(stringSerializer);
                redisTemplate.opsForValue().set(SecurityConstant.USER_QYWX + user.getUsername(), wxcode, 300, TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(SecurityConstant.XBOOT_USER_CODE_EXPIRE + user.getUsername(), exiperTime, 300, TimeUnit.SECONDS);
            }else{
                return new ResultUtil<>().setErrorMsg(errotMsg);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResultUtil<Object>().setErrorMsg(errotMsg);
        }
        return new ResultUtil<Object>().setSuccessMsg("已发送app动态码，注意查看");
    }

    /**
     * @author    : LiYuanzhuo
     * description: 校验app动态码
     *
     * create time: 2019/9/3 13:35
     */
    @RequestMapping(value = "/verifyCode",method = RequestMethod.POST)
    public Result<Object> verifyCode(@RequestParam String username,@RequestParam String code){
        User user = userService.findByUsername(username);
        if (user == null) {
            return new ResultUtil<Object>().setErrorMsg("用户不存在");
        }
        redisTemplate = (StringRedisTemplate) SpringContextUtil.getBean("stringRedisTemplate");
        String sendWxcode = (String) redisTemplate.opsForValue().get(SecurityConstant.USER_QYWX + user.getUsername());
        if (sendWxcode == null){
            return new ResultUtil<>().setErrorMsg("未给当前用户发送app验证码！");
        }
        if (!sendWxcode.equals(code)){
            return new ResultUtil<>().setErrorMsg("输入的验证码错误");
        }
        redisTemplate.delete(SecurityConstant.USER_QYWX + user.getUsername());

        return new ResultUtil<>().setSuccessMsg("校验通过");
    }

}
